from src.util.Route import *
from src.service import MsgService
from src.util.JwtUtil import authToken
from flask_socketio import disconnect


# 发送
@route('/msg/send/inform', methods=['POST'])
def messageInform():
    data = request.json
    data['send'] = getUsername()
    r = MsgService.sendInform(data)
    if r:
        return R.success(None, '发送成功')
    return R.bad_request("发送失败")


# 删除
@route('/msg/del', methods=['POST'])
def messageDel():
    data = request.json
    r = MsgService.delMsg(data)
    if r:
        return R.success(None, '删除成功')
    return R.bad_request("删除失败")


# 查询
@route('/msg/get', methods=['POST'])
def messageGet():
    data = request.json
    page = data.get("page")
    cdn = data.get("cdn")
    if cdn is None:
        cdn = {}
    page = Page(num=page['num'], size=page['size'])
    r = MsgService.getMsg(page, cdn)
    return R.success(r)


@route('/msg/sold_out', methods=['PUT'])
def msgUpdate():
    data: dict = request.json
    r = MsgService.updateStatus(data.get('ids'), '0')
    if r:
        return R.success(True, '操作成功')
    return R.bad_request("操作失败")


# 链接
@socket.on('connect')
def connected_msg():
    token = getToken()
    # 验证token 有效性
    info: dict = authToken(token)
    if not info:
        socket.send('', json=True, close=True)
        disconnect()
        return
    user = info.get('username')
    MsgService.save(user, request.sid)


# 断开链接
@socket.on('disconnect')
def disconnect_msg():
    token = getToken()
    info: dict = authToken(token)
    if not info:
        disconnect()
        return
    MsgService.delSid(info.get('username'), request.sid)
    disconnect()
